package com.example.myapplication.blue.connect;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

///已连接线程
public class ConnectedThread extends Thread {
    ///蓝牙套接字
    private final BluetoothSocket mmSocket;
    ///输入流
    private final InputStream mmInStream;
    ///输出流
    private final OutputStream mmOutStream;
    ///线程
    private final Handler mHandler;


    ///已连接线程
    public ConnectedThread(BluetoothSocket socket, Handler handler) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        mHandler = handler;
        // 使用临时对象获取输入和输出流，因为成员流是最终的
        try {
            ///从嵌套字获取输入输出流
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {

        }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


    ///已连接线程执行
    public void run() {
        //创建长度为1024的空byte 用于流的缓冲存储
        byte[] buffer = new byte[1024];
        // 从read()返回bytes
        int bytes;

        // 持续监听InputStream，直到出现异常
        while (true) {
            try {
                // 从输入流读取数据
                bytes = mmInStream.read(buffer);
                // 如果获得的将获得的bytes数据大于0，则发送到UI层activity
                if( bytes >0) {
                    Message message = mHandler.obtainMessage(
                            // 获取到数据
                            Constant.MSG_GOT_DATA,
                            //通过utf-8编码，buffer生成string数据
                            new String(buffer, 0, bytes, "utf-8")
                    );
                    //发送数据
                    mHandler.sendMessage(message);
                }
                Log.d("GOTMSG", "message size" + bytes);
            } catch (IOException e) {
                ///线程发送消息：出错
                mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR, e));
                break;
            }
        }

    }

    //写数据
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {

        }
    }

    //关闭嵌套字
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
